<template>
  <div class="app-container">

        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="题目名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入题目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="试题类型" prop="quType">
            <el-select v-model="queryParams.quType" placeholder="请选择试题类型" clearable>
              <el-option
                v-for="dict in dict.type.qu_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="分类" prop="type">
            <div class="treeselect" style="width: 300px">
              <treeselect v-model="queryParams.type" :options="typeOptionsSelect"
                          :show-count="true"      :normalizer="normalizer" @select="handleNodeClickquery" placeholder="选择类型"/>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-if="viewType!='selectqu'"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:question:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              v-if="viewType!='selectqu'"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:question:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              v-if="viewType!='selectqu'"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:question:remove']"
            >删除</el-button>
          </el-col>

          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            v-if="viewType=='selectqu'"
            @click="confirmSelect"
          >确定选择</el-button>
         <el-col :span="1.5">
                      <el-button
                        type="info"
                        plain
                        icon="el-icon-upload2"
                        size="mini"
                        v-if="viewType!='selectqu'"
                        @click="handleImport('1')"
                      >导入选择题
         </el-button>
             <el-button
               type="info"
               plain
               icon="el-icon-upload2"
               size="mini"
               @click="handleImport('2')"
               v-if="viewType!='selectqu'"
             >导入判断题
             </el-button>
         </el-col>




          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
<!--          <el-table-column label="主键" align="center" prop="id" />-->
          <el-table-column label="题目名称" align="center" prop="title" />
          <el-table-column label="试题类型" align="center" prop="quType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.qu_type" :value="scope.row.quType"/>
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" prop="typeName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-if="viewType!='selectqu'"
                v-hasPermi="['system:question:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-if="viewType!='selectqu'"
                v-hasPermi="['system:question:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />



    <!-- 添加或修改试题信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入题目名称" />
        </el-form-item>
        <el-form-item label="试题类型" prop="quType">
          <el-select v-model="form.quType" placeholder="请选择试题类型"  @change="quTypeSelectChange">
            <el-option
              v-for="dict in dict.type.qu_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="type">
          <div class="treeselect">
            <treeselect v-model="form.type" :options="typeOptionsSelect"
                        :show-count="true"      :normalizer="normalizer" @select="handleNodeClick" placeholder="选择类型"/>
          </div>
        </el-form-item>


        <el-form-item label="选项" prop="optionList">
          <div v-for="(item,index) in form.optionList"   v-if="form.quType=='1'"   class="plr15">
            <div class="mtb10 df  dfsb">
              <div style="width: 30%">
            <span >
              <el-checkbox v-model="item.isRight"  @change="checked=>checboxchange(checked,index)"  ></el-checkbox>
            </span>
                <span>
             {{item.options}}、选项
           </span>
                <span>
              </span>
              </div >
              <div style="width: 30%">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteSelectOption(index)"
                >删除</el-button>
                <!--              <img   style=" width: 25px; height: 25px;cursor:pointer" @click="deleteSelectOption(index)" src="@/assets/images/ch.png" alt="删除">-->
              </div>
            </div>
            <el-input  type="textarea" :rows="2" v-model="item.title" :min-height="192"/>
          </div>

          <div  class="text-center ptb20 " v-if="form.quType=='1'" >
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addSelectOption"
            >添加一个选项</el-button>
          </div>


          <div style="margin-bottom: 20px;" v-if="form.quType=='2' ">
            <span v-for="(item,index) in form.optionList"  class="plr15">
            <span  style="margin-left: 20px">
              <el-checkbox v-model="item.isRight"  @change="checked=>checboxchange(checked,index)"  ></el-checkbox>
            </span>
            <span>
             {{item.options}}
           </span>
          </span>
          </div>

        </el-form-item>



        <el-form-item label="答案解析" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm"  v-if="title!='试题信息'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/business/question";
import { listType, getType, delType, addType, updateType,typeTreeSelect } from "@/api/business/qutype";
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/system/user'
import { getToken } from '@/utils/auth'
export default {
  name: "Question",
  dicts: ['qu_type'],
  props: {
    viewType: {
      type: String,
      default: null
    }
  },
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中数组
      ids: [],
      name:"",
      showTree:false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题信息表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        quType: null,
        type: null,
        content: null,
      },
      multipleSelection:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title : [
          { required: true, message: "题目名称不能为空", trigger: "blur" }
        ],
        quType : [
          { required: true, message: "试题类型不能为空", trigger: "blur" }
        ],
        type : [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        content : [
          { required: true, message: "答案解析不能为空", trigger: "blur" }
        ]

      },
      typeOptions:[],
      typeOptionsSelect:[],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/business/question/importData'
      },
      quTypeImport:"",
    };
  },

  created() {
    this.getList();
    listType().then(response => {
      this.typeOptionsSelect = this.handleTree(response.data, "id");
    });
  },
  mounted() {
    // this.getTypeTree()
    // this.getTypeTree()
  },
  methods: {
    handleImport(type) {
      if(type=='1'){
        this.upload.title = '单选试题导入'
      }else{
        this.upload.title = '判断试题导入'
      }
      this.upload.open = true
      if(type=='2'){
        this.upload.url=process.env.VUE_APP_BASE_API + '/business/question/importDataPd'
      }
      this.quTypeImport=type

    },
    getTypeTree() {
      typeTreeSelect().then(response => {
        this.typeOptions = response.data
        this.showTree=true
      })
    },
    handleTypeNodeClick(data) {
      this.queryParams.type = data.id
      this.handleQuery()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data){
      if(data.parentId=='0'){
        this.$modal.msgError("请选择二级节点");
        // 怎么调用 clear value

        this.form.type = null;
        this.$nextTick(() => {
          // 确保 DOM 更新后清空选择
          this.$refs.form.clearValidate('type');
        })
      }
      return;
    },

    handleNodeClickquery(data){

    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    quTypeSelectChange(value){
      //  1   选择   2 判断题
      if(value=='1'   ){
        this.initTipsSelectAnwser()
      }else {
        // 判断题
        this.initPdtAnwser()
      }

    },
    initTipsSelectAnwser(){
      this.$set(this.form,"optionList",[])
      for (let i = 0; i < 4; i++) {
        // 录入答案提示
        var  answertipsform = {
          id: null,
          quId: null,
          isRight: null,
          options: 'A',
          title: null,
          orderNum: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        if(i==0){
          answertipsform.options="A";
        }else{
          var  con=this.form.optionList[i-1].options;
          answertipsform.options=String.fromCharCode(con.charCodeAt(0) + 1);
        }
        this.form.optionList.push(answertipsform)
      }
    },

    initPdtAnwser(){
      this.$set(this.form,"optionList",[])
      var answerformfirst = {
        id: null,
        quId: null,
        isRight: null,
        options: '对',
        title: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      var answerformsecond = {
        id: null,
        quId: null,
        isRight: null,
        options: '错',
        title: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.form.optionList.push(answerformfirst)
      this.form.optionList.push(answerformsecond)

    },

    checboxchange(value,index){
      if(value ){
        this.form.optionList.forEach((item,i) => {
          if(i!=index){
            item.isRight=false;
            this.form.optionList.splice(i,1,item)
          }
        });
      }

    },
    deleteSelectOption(index){
      if(this.form.optionList.length==1){
        this.$modal.msgError("至少一个选项");
        return
      }
      this.form.optionList.splice(index,1)
      // 选项A bcd 重新生成
      for (let i = 0; i <  this.form.optionList.length; i++) {
        var  item=this.form.optionList[i];
        if(i==0){
          item.options="A";
        }else{
          var  con=this.form.optionList[i-1].options;
          item.options=String.fromCharCode(con.charCodeAt(0) + 1);
        }
        this.form.options.splice(i,1,item)
      }
    },

    addSelectOption(){
      // 单选和多选
      var length= this.form.optionList.length;
      var lastzm= this.form.optionList[length-1].options
      var answerform ={
        id: null,
        quId: null,
        isRight: null,
        options: 'A',
        title: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      answerform.options=String.fromCharCode(lastzm.charCodeAt(0) + 1);
      this.form.optionList.push(answerform)

    },
    /** 查询试题信息列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        quType: null,
        type: null,
        content: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        optionList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection=selection;
      console.log(selection,"====================")
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题信息";
      this.form.quType='1'
      this.initTipsSelectAnwser()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data;
        this.form.optionList.forEach((item,i) => {
          if(item.isRight=="true"){
            item.isRight=true;
          }else if(item.isRight=="false"){
            item.isRight=false;
          }
          this.form.optionList.splice(i,1,item)
        });
        this.open = true;
        this.title = "修改试题信息";
      });
    },

    /** 修改按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data;
        this.form.optionList.forEach((item,i) => {
          if(item.isRight=="true"){
            item.isRight=true;
          }else if(item.isRight=="false"){
            item.isRight=false;
          }
          this.form.optionList.splice(i,1,item)
        });
        this.open = true;
        this.title = "试题信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除试题信息编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    confirmSelect() {
      // 获取选的试题数据
      console.log('选中的数据行:', this.multipleSelection);
      // 传递个父组件
      this.$emit('selectQuestion',this.multipleSelection)

    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('business/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      if(this.quTypeImport=='1'){
        this.download('business/question/importTemplate', {}, `qustion_template_${new Date().getTime()}.xlsx`)
      }else{
        this.download('business/question/importTemplatePd', {}, `qustion_template_${new Date().getTime()}.xlsx`)
      }

    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 100vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
};
</script>
